/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys;

import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.ResponseResult;
import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.modules.messages.dao.EleEquipmentMessagesDao;
import com.thinkgem.jeesite.modules.messages.entity.EleEquipmentMessages;

import java.util.Date;

/**
 * 字典工具类
 * @author ThinkGem
 * @version 2014-11-7
 */
public class MessagesUtils{
	private static EleEquipmentMessagesDao dao = SpringContextHolder.getBean(EleEquipmentMessagesDao.class);

	/**
	 * 保存日志
	 */
	public static String saveRequestMessages(String method, String mac, Object data, Long time){
		return saveMessages("request", "", method, ResponseResult.SUCCESS, mac, data, time);
	}

    public static void saveResponseMessages(String method, String forRequest, ResponseResult result){
        saveMessages("response", forRequest, method, result.getCode(), result.getMac(), result.getData(), result.getTime());
	}

    /**
     * 保存日志
     */
	public static String saveMessages(String type, String forRequest, String method, String code, String mac, Object data, Long time){
		Date date = null;
		try{
			date = new Date(time);
		}catch(Exception e){
			date = new Date(System.currentTimeMillis());
		}
        EleEquipmentMessages messages = new EleEquipmentMessages();
        messages.setType(type);
        messages.setForrequest(forRequest);
        messages.setMethod(method);
        messages.setCode(code);
        messages.setMac(mac);
        messages.setData(null == data?"": JsonMapper.toJsonString(data));
        messages.setTime(date);
        messages.preInsert();
        // 异步保存日志
        new SaveMessagesThread(messages).start();
        return messages.getId();
    }

	/**
	 * 保存日志线程
	 */
	public static class SaveMessagesThread extends Thread{

		private EleEquipmentMessages messages;

		SaveMessagesThread(EleEquipmentMessages messages){
			super(MessagesUtils.SaveMessagesThread.class.getSimpleName());
			this.messages = messages;
		}

		@Override
		public void run() {
			// 保存日志信息
			dao.insert(messages);
		}
	}
}
